package com.ytd.smartcanteen.weighting.util;


import android.text.TextUtils;

import com.ytd.common.base.BaseApplication;
import com.ytd.common.bean.BaseRequest;
import com.ytd.common.bean.BaseResponse;
import com.ytd.common.bean.request.BaseRequestData;
import com.ytd.common.net.NetCallBack;
import com.ytd.common.net.RequestManager;
import com.ytd.common.util.DateUtil;
import com.ytd.common.util.GsonUtil;
import com.ytd.common.util.LocalDataManager;
import com.ytd.common.util.LogUtil;
import com.ytd.common.util.ThreadUtil;
import com.ytd.common.util.YtdConfig;
import com.ytd.smartcanteen.weighting.bean.MealCategoryInfo;
import com.ytd.smartcanteen.weighting.bean.MealInfo;
import com.ytd.smartcanteen.weighting.bean.MealTimeInfo;
import com.ytd.smartcanteen.weighting.bean.OrderBean;
import com.ytd.smartcanteen.weighting.bean.request.GetFoodPageRequestData;
import com.ytd.smartcanteen.weighting.bean.response.GetFoodCategoryResponse;
import com.ytd.smartcanteen.weighting.bean.response.GetFoodInfoListResponse;
import com.ytd.smartcanteen.weighting.bean.response.GetFoodInfoResponse;
import com.ytd.smartcanteen.weighting.bean.response.GetFoodPageResponse;
import com.ytd.smartcanteen.weighting.bean.response.UpdateFoodResponse;
import com.ytd.smartcanteen.weighting.bean.response.UpdateMealTimeResponse;
import com.ytd.smartcanteen.weighting.constants.Constants;
import com.ytd.smartcanteen.weighting.dao.MealCategoryInfoDao;
import com.ytd.smartcanteen.weighting.dao.MealInfoDao;
import com.ytd.smartcanteen.weighting.dao.MealTimeInfoDao;
import com.ytd.smartcanteen.weighting.dao.OrderBeanDao;
import com.ytd.smartcanteen.weighting.dao.WeightingDB;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 食品管理类
 *
 * @author gaoguanchao
 * @since 2023/4/20
 */
public class FoodManager {

    private final Map<String, MealInfo> mCurrentBindingMeals = new HashMap<>();
    private final List<MealInfo> mCurrentBindingMealList = new ArrayList<>();
    private final Map<String, MealTimeInfo> mMealTimes = new HashMap<>();
    private MealInfo mCurrentMealInfo;

    private FoodChangeCallBack mCallBack;

    private boolean isInit;

    public void init(FoodChangeCallBack callBack) {
        if (isInit) {
            return;
        }
        this.mCallBack = callBack;
        EventBus.getDefault().register(this);
        isInit = true;
        loadLocalMeal();
        matchMeal();
        MealTimeInfoDao mealTimeInfoDao = WeightingDB.getInstance().getMealTimeInfoDao();
        initMealTimes(mealTimeInfoDao.getAll());
    }

    private void initMealTimes(List<MealTimeInfo> mealTimeInfoList) {
        mMealTimes.clear();
        for (MealTimeInfo mealTimeInfo : mealTimeInfoList) {
            mMealTimes.put(mealTimeInfo.mealTimeId, mealTimeInfo);
        }
    }

    public void initData() {
        initBindFood();
        MealTimeInfoDao mealTimeInfoDao = WeightingDB.getInstance().getMealTimeInfoDao();
        int count = mealTimeInfoDao.getCount();
        if (count == 0) {
            initFoodData();
        }
    }

    public void initBindFood() {
        getFoodInfo();
        getFoodInfoList();
    }

    public void initFoodData() {
        isGetFoodCategory = false;
        getMealTimeList();
        getFoodCategory();
    }

    public boolean isMealTimeBound(String mealTimeId) {
        return mCurrentBindingMeals.get(mealTimeId) != null;
    }

    public boolean isCategoryBound(String mealTimeId, String categoryId) {
        MealInfo mealInfo = mCurrentBindingMeals.get(mealTimeId);
        if (mealInfo == null) {
            return false;
        }
        return mealInfo.foodCategoryId.equals(categoryId);
    }

    public Map<String, MealInfo> getCurrentBindingMeals() {
        return mCurrentBindingMeals;
    }

    public MealInfo getCurrentMealInfo() {
        return mCurrentMealInfo;
    }

    public List<MealInfo> getCurrentBindingMealList() {
        return mCurrentBindingMealList;
    }

    public void release() {
        isInit = false;
        mCallBack = null;
        EventBus.getDefault().unregister(this);
    }


    private void getMealTimeList() {
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.interfaceName = Constants.GET_MEAL_TIME_LIST;
        baseRequest.data = new BaseRequestData();
        RequestManager.getInstance().request(baseRequest, new NetCallBack<List<MealTimeInfo>>() {
            @Override
            public void onSuccess(List<MealTimeInfo> result) {
                MealTimeInfoDao mealTimeInfoDao = WeightingDB.getInstance().getMealTimeInfoDao();
                mealTimeInfoDao.deleteAll();
                mMealTimes.clear();
                for (MealTimeInfo mealTimeInfo : result) {
                    mealTimeInfoDao.insert(mealTimeInfo);
                    mMealTimes.put(mealTimeInfo.mealTimeId, mealTimeInfo);
                    LogUtil.d("mealTimeInfoDao.insert：" + mealTimeInfo.mealTimeName);
                }
            }

            @Override
            public void onFail(int code, String msg) {
                LogUtil.d("getMealTimeList onFail " + code + "---" + msg);
            }
        });
    }

    private boolean isGetFoodCategory;

    public MealTimeInfo getMealTime(String mealTimeId) {
        return mMealTimes.get(mealTimeId);
    }

    private void getFoodCategory() {
        if (isGetFoodCategory) {
            return;
        }
        isGetFoodCategory = true;
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.interfaceName = Constants.GET_FOOD_CATEGORY;
        baseRequest.data = new BaseRequestData();
        RequestManager.getInstance().request(baseRequest, new NetCallBack<List<GetFoodCategoryResponse>>() {

            @Override
            public void onSuccess(List<GetFoodCategoryResponse> result) {
                processFoodCategory(result);
            }

            @Override
            public void onFail(int code, String msg) {
                LogUtil.d("getFoodCategory onFail " + code + "---" + msg);
            }
        });
    }

    private void processFoodCategory(List<GetFoodCategoryResponse> result) {
        ThreadUtil.execute(() -> {
            MealCategoryInfoDao mealCategoryInfoDao = WeightingDB.getInstance().getMealCategoryInfoDao();
            if (!result.isEmpty()) {
                mealCategoryInfoDao.deleteAll();
                MealInfoDao mealInfoDao = WeightingDB.getInstance().getMealInfoDao();
                mealInfoDao.deleteAll();
                for (int i = 0; i < result.get(0).foodCategories.size(); i++) {
                    MealCategoryInfo categoryInfo = result.get(0).foodCategories.get(i);
                    categoryInfo.mealTimeId = result.get(0).mealTimeId;
                    categoryInfo.mealTimeName = result.get(0).mealTimeName;
                    mealCategoryInfoDao.insert(categoryInfo);
                    getFoodPage(result.get(0).mealTimeId, categoryInfo.id, categoryInfo.categoryName,
                            i == result.get(0).foodCategories.size() - 1);
                    LogUtil.d("mealCategoryInfoDao.insert：" + categoryInfo.categoryName);
                }
            }
        });
    }

    private void getFoodPage(String mealTimeId, String foodCategoryId, String categoryName, boolean isLast) {
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.interfaceName = Constants.GET_FOOD_PAGE;
        GetFoodPageRequestData getFoodPageRequestData = new GetFoodPageRequestData();
        getFoodPageRequestData.foodCategoryId = foodCategoryId;
        getFoodPageRequestData.mealTimeId = mealTimeId;
        baseRequest.data = getFoodPageRequestData;
        if (isLast) {
            BaseResponse response = new BaseResponse();
            response.interfaceName = Constants.GET_FOOD_PAGE_END;
            EventBus.getDefault().post(response);
            isGetFoodCategory = false;
            WeightConfig.setSyncTime(System.currentTimeMillis());
        }
        RequestManager.getInstance().request(baseRequest, new NetCallBack<GetFoodPageResponse>() {
            @Override
            public void onSuccess(GetFoodPageResponse result) {
                ThreadUtil.execute(() -> {
                    if (result.total > 0 && result.list != null) {
                        MealInfoDao mealInfoDao = WeightingDB.getInstance().getMealInfoDao();
                        for (MealInfo mealInfo : result.list) {
                            mealInfo.foodCategoryId = foodCategoryId;
                            mealInfo.foodCategoryName = categoryName;
                            mealInfoDao.insert(mealInfo);
                            LogUtil.d("mealInfoDao.insert：" + mealInfo.foodName);
                        }
                    }
                });
            }

            @Override
            public void onFail(int code, String msg) {
                LogUtil.d("getFoodPage onFail " + code + "---" + msg);
            }
        });
    }

    private void getFoodInfoList() {
        if (BaseApplication.getInstance().isLocalMode() && mCurrentBindingMealList.isEmpty()) {
            loadLocalMeal();
            return;
        }
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.interfaceName = Constants.GET_FOOD_INFO_LIST;
        baseRequest.data = new BaseRequestData();
        RequestManager.getInstance().request(baseRequest, new NetCallBack<GetFoodInfoListResponse>() {
            @Override
            public void onSuccess(GetFoodInfoListResponse result) {
                mCurrentBindingMeals.clear();
                mCurrentBindingMealList.clear();
                if (result.mealInfos != null && !result.mealInfos.isEmpty()) {
                    mCurrentBindingMealList.addAll(result.mealInfos);
                    WeightConfig.setCurrentMeals(mCurrentBindingMealList);
                    for (MealInfo mealInfo : result.mealInfos) {
                        mCurrentBindingMeals.put(mealInfo.mealTimeId, mealInfo);
                    }
                } else {
                    WeightConfig.setCurrentMeals(mCurrentBindingMealList);
                    sendNoBindingEvent();
                }
                YtdConfig.setMerchantName(result.merchantName);
            }

            @Override
            public void onFail(int code, String msg) {
                loadLocalMeal();
                LogUtil.d("getFoodInfoList onFail " + code + "---" + msg);
            }
        });
    }

    private void sendNoBindingEvent() {
        if (mCurrentBindingMealList.isEmpty()) {
            BaseResponse response = new BaseResponse();
            response.interfaceName = Constants.NO_BINDING_ERROR;
            EventBus.getDefault().post(response);
        }
    }

    public void getFoodInfo() {
        if (BaseApplication.getInstance().isLocalMode()) {
            LogUtil.d("isLocalMode matchMeal");
            matchMeal();
            return;
        }
        if (mCurrentBindingMealList.isEmpty()) {
            getFoodInfoList();
        }
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.interfaceName = Constants.GET_FOOD_INFO;
        baseRequest.data = new BaseRequestData();
        RequestManager.getInstance().request(baseRequest, new NetCallBack<GetFoodInfoResponse>() {

            @Override
            public void onSuccess(GetFoodInfoResponse result) {
                if (result.mealInfo != null) {
                    result.mealInfo.inMeal = result.inMeal;
                }
                resetCurrentMealInfo(result.mealInfo);
                uploadLocalOrder(result.mealInfo);
            }

            @Override
            public void onFail(int code, String msg) {
                matchMeal();
                LogUtil.d("getFoodInfo onFail " + code + "---" + msg);
            }
        });
    }

    private void uploadLocalOrder(MealInfo mealInfo) {
        if (LocalDataManager.getInstance().isStart() || mealInfo == null) {
            return;
        }
        OrderBeanDao orderBeanDao = WeightingDB.getInstance().getOrderBeanDao();
        String mealTimeId = mealInfo.mealTimeId;
        if (mMealTimes.size() <= 1) {
            mealTimeId = "";
        }
        final String localMealTimeId = mealTimeId;
        LocalDataManager.getInstance().setLocalDataCallBack(new LocalDataManager.LocalDataCallBack<OrderBean>() {
            @Override
            public List<OrderBean> getData(int start, int pageSize) {
                return orderBeanDao.getLocalOrderLimit(localMealTimeId, start, pageSize);
            }

            @Override
            public int getCount() {
                return orderBeanDao.getLocalOrderCount(localMealTimeId);
            }

            @Override
            public int getUploadedCount() {
                return orderBeanDao.getLocalOrderUploadedCount(localMealTimeId);
            }

            @Override
            public String getInterfaceName() {
                return Constants.BATCH_ADD_OFFLINE_ORDER_SNAPSHOT;
            }

            @Override
            public void update(OrderBean orderBean) {
                orderBean.uploadState = 1;
                orderBeanDao.update(orderBean);
            }

            @Override
            public void deleteUploadData() {
                orderBeanDao.deleteUploadData();
            }
        });
        LocalDataManager.getInstance().startUpload();
    }

    private FoodManager() {
    }

    public static FoodManager getInstance() {
        return ManagerHolder.instance;
    }

    public MealCategoryInfo updateFoodCategory(@NotNull BaseResponse response) {
        MealCategoryInfo categoryInfo =
                GsonUtil.fromJsonForObj(response.data, MealCategoryInfo.class);
        MealCategoryInfoDao mealCategoryInfoDao = WeightingDB.getInstance().getMealCategoryInfoDao();
        mealCategoryInfoDao.update(categoryInfo);
        MealInfoDao mealInfoDao = WeightingDB.getInstance().getMealInfoDao();
        mealInfoDao.updateCategoryInfo(categoryInfo.id, categoryInfo.categoryName);
        initBindFood();
        LogUtil.d("updateFoodCategory " + categoryInfo.id);
        return categoryInfo;
    }

    public MealInfo updateFood(@NotNull BaseResponse response) {
        UpdateFoodResponse updateFoodResponse =
                GsonUtil.fromJsonForObj(response.data, UpdateFoodResponse.class);
        MealInfoDao mealInfoDao = WeightingDB.getInstance().getMealInfoDao();
        MealInfo mealForId = mealInfoDao.getMealForId(updateFoodResponse.id);
        if (updateFoodResponse.deleted == 1 || updateFoodResponse.enabled == 0) {
            if (mealForId != null) {
                mealInfoDao.delete(mealForId);
            }
            return null;
        }
        if (mCurrentMealInfo != null && mealForId.foodId.equals(mCurrentMealInfo.foodId)) {
            getFoodInfo();
        }
        if (mealForId == null) {
            mealForId = new MealInfo();
            mealForId.foodId = updateFoodResponse.id;
            mealInfoDao.insert(mealForId);
        }
        mealForId.foodCategoryId = updateFoodResponse.categoryId;
        if (TextUtils.isEmpty(mealForId.foodCategoryName)) {
            MealCategoryInfoDao mealCategoryInfoDao = WeightingDB.getInstance().getMealCategoryInfoDao();
            MealCategoryInfo categoryForId = mealCategoryInfoDao.getCategoryForId(mealForId.foodCategoryId);
            if (categoryForId != null) {
                mealForId.foodCategoryName = categoryForId.categoryName;
            }
        }
        mealForId.clipWeight = updateFoodResponse.clipWeight;
        mealForId.calcType = updateFoodResponse.calcType;
        mealForId.foodName = updateFoodResponse.foodName;
        mealForId.foodLogo = updateFoodResponse.logo;
        mealForId.price = String.valueOf(updateFoodResponse.price);
        mealForId.priceUnit = updateFoodResponse.priceUnit;
        mealForId.numberUnit = updateFoodResponse.numberUnit;
        mealForId.numberUnitName = updateFoodResponse.numberUnitName;
        mealForId.remark = updateFoodResponse.remark;
        mealForId.weight = updateFoodResponse.weight;
        mealForId.weightUnit = updateFoodResponse.weightUnit;
        mealForId.floatingWeight = updateFoodResponse.floatingWeight;
        mealForId.onePortionWeight = updateFoodResponse.onePortionWeight;
        mealForId.whetherLimitWeightOfTake = updateFoodResponse.whetherLimitWeightOfTake;
        mealForId.limitWeightOfTake = updateFoodResponse.limitWeightOfTake;
        mealForId.startingWeight = updateFoodResponse.startingWeight;
        mealInfoDao.update(mealForId);
        for (MealInfo mealInfo : mCurrentBindingMealList) {//绑定列表有该餐品时，更新绑定列表
            if (mealForId.foodId.equals(mealInfo.foodId)) {
                getFoodInfoList();
                break;
            }
        }
        LogUtil.d("updateFood " + mealForId.foodId + "----" + mealForId.foodName);
        return mealForId;
    }


    public List<MealTimeInfo> getData() {
        MealTimeInfoDao mealTimeInfoDao = WeightingDB.getInstance().getMealTimeInfoDao();
        List<MealTimeInfo> all = mealTimeInfoDao.getAll();
        MealCategoryInfoDao mealCategoryInfoDao = WeightingDB.getInstance().getMealCategoryInfoDao();
        MealInfoDao mealInfoDao = WeightingDB.getInstance().getMealInfoDao();
        List<MealCategoryInfo> categoryInfos = mealCategoryInfoDao.getAll();
        List<MealCategoryInfo> emptyList = new ArrayList<>();
        for (MealCategoryInfo categoryInfo : categoryInfos) {
            categoryInfo.mMealInfos = mealInfoDao.getMealForCategory(categoryInfo.id);
            if (categoryInfo.mMealInfos == null || categoryInfo.mMealInfos.isEmpty()) {
                emptyList.add(categoryInfo);
            }
        }

        for (MealCategoryInfo categoryInfo : emptyList) {
            categoryInfos.remove(categoryInfo);
        }

        for (MealTimeInfo mealTimeInfo : all) {
            mealTimeInfo.mMealCategoryInfos = new ArrayList<>(categoryInfos);
        }
        return all;
    }

    public List<MealInfo> searchFoodPageList(String categoryId, String text) {
        MealInfoDao mealInfoDao = WeightingDB.getInstance().getMealInfoDao();
        return mealInfoDao.getMealLikeName("%" + text + "%");
    }

    public void setFoodInfo(@NotNull BaseResponse response) {
        GetFoodInfoResponse foodInfoResponse = GsonUtil.fromJsonForObj(response.data, GetFoodInfoResponse.class);
        MealInfo responseMealInfo = foodInfoResponse.mealInfo;
        if (responseMealInfo == null) {
            return;
        }

        if (updateBindFoods(responseMealInfo)) {
            return;
        }

        if (mCurrentMealInfo != null && mCurrentMealInfo.mealTimeId.equals(responseMealInfo.mealTimeId)) {
            resetCurrentMealInfo(responseMealInfo);
        }
    }

    public void setFoodInfoList(@NotNull BaseResponse response) {
        getFoodInfo();
        getFoodInfoList();
    }

    private boolean updateBindFoods(MealInfo responseMealInfo) {
        mCurrentBindingMeals.put(responseMealInfo.mealTimeId, responseMealInfo);
        MealInfo tmpMealInfo = null;
        for (MealInfo mealInfo : mCurrentBindingMealList) {
            if (mealInfo.mealTimeId.equals(responseMealInfo.mealTimeId)) {
                tmpMealInfo = mealInfo;
                break;
            }
        }
        if (tmpMealInfo == null) {
            initBindFood();
            return true;
        }
        int i = mCurrentBindingMealList.indexOf(tmpMealInfo);
        if (i != -1) {
            mCurrentBindingMealList.remove(tmpMealInfo);
            mCurrentBindingMealList.add(i, responseMealInfo);
            WeightConfig.setCurrentMeals(mCurrentBindingMealList);
        }
        return false;
    }

    private void updateBindList(String mealTimeId, MealInfo newMealInfo) {
        MealInfo mealInfo1 = mCurrentBindingMeals.get(mealTimeId);
        if (mealInfo1 != null) {
            appendMealTimeInfo(newMealInfo, mealInfo1);
        } else {
            MealTimeInfo mealTimeForId = getMealTime(mealTimeId);
            newMealInfo.mealStartTime = mealTimeForId.mealStartTime;
            newMealInfo.mealEndTime = mealTimeForId.mealEndTime;
            newMealInfo.mealTimeId = mealTimeForId.mealTimeId;
            newMealInfo.mealTimeName = mealTimeForId.mealTimeName;
        }
        mCurrentBindingMeals.put(mealTimeId, newMealInfo);
        MealInfo tmpMealInfo = null;
        for (MealInfo mealInfo : mCurrentBindingMealList) {
            if (mealInfo.mealTimeId.equals(mealTimeId)) {
                tmpMealInfo = mealInfo;
            }
        }
        int i = mCurrentBindingMealList.indexOf(tmpMealInfo);
        if (i != -1) {
            mCurrentBindingMealList.remove(tmpMealInfo);
            mCurrentBindingMealList.add(i, newMealInfo);
            WeightConfig.setCurrentMeals(mCurrentBindingMealList);
        }
    }

    private static void appendMealTimeInfo(MealInfo newMealInfo, MealInfo mealInfo1) {
        newMealInfo.mealTimeId = mealInfo1.mealTimeId;
        newMealInfo.mealStartTime = mealInfo1.mealStartTime;
        newMealInfo.mealEndTime = mealInfo1.mealEndTime;
        newMealInfo.mealTimeName = mealInfo1.mealTimeName;
        newMealInfo.mealTimeTypeCode = mealInfo1.mealTimeTypeCode;
    }

    public void checkMeal(@NotNull MealInfo mealInfo) {
        boolean nowEffectiveDate = DateUtil.isNowEffectiveDate(mealInfo.mealStartTime,
                mealInfo.mealEndTime);
        if (nowEffectiveDate) {
            mCurrentMealInfo = mealInfo;
            mCurrentMealInfo.inMeal = true;
            if (mCallBack != null) {
                mCallBack.onMealChange(mCurrentMealInfo);
            }
        }
    }

    public void resetCurrentMealInfo(MealInfo responseMealInfo) {
        mCurrentMealInfo = responseMealInfo;
        if (mCurrentMealInfo != null) {
            mCurrentMealInfo.inMeal = DateUtil.isNowEffectiveDate(mCurrentMealInfo.mealStartTime,
                    mCurrentMealInfo.mealEndTime);
        }
        LogUtil.d("resetCurrentMealInfo :" + mCurrentMealInfo);
        if (mCallBack != null) {
            mCallBack.onMealChange(mCurrentMealInfo);
        }
    }

    public boolean updateMealTime(@NotNull BaseResponse response) {
        UpdateMealTimeResponse updateMealTimeResponse =
                GsonUtil.fromJsonForObj(response.data, UpdateMealTimeResponse.class);
        MealTimeInfoDao mealTimeInfoDao = WeightingDB.getInstance().getMealTimeInfoDao();
        MealTimeInfo mealTimeForId = mealTimeInfoDao.getMealTimeForId(updateMealTimeResponse.id);
        MealInfo mealInfo = mCurrentBindingMeals.get(updateMealTimeResponse.id);
        if (mealInfo == null || mealTimeForId == null) {//本地表没有这个餐别
            getMealTimeList();
            initBindFood();
            return false;
        }
        if (updateMealTimeResponse.deleted == 1 || updateMealTimeResponse.enabled == 0) {
            mealTimeInfoDao.delete(mealTimeForId);
            mMealTimes.remove(updateMealTimeResponse.id);
            mCurrentBindingMeals.remove(updateMealTimeResponse.id);
            mCurrentBindingMealList.remove(mealInfo);
            WeightConfig.setCurrentMeals(mCurrentBindingMealList);
        } else {
            mealTimeForId.mealStartTime = updateMealTimeResponse.startTime;
            mealTimeForId.mealEndTime = updateMealTimeResponse.endTime;
            mealTimeForId.mealTimeTypeCode = updateMealTimeResponse.mealTimeTypeCode;
            mealTimeInfoDao.update(mealTimeForId);
            mMealTimes.put(updateMealTimeResponse.id, mealTimeForId);
            mealInfo.mealStartTime = mealTimeForId.mealStartTime;
            mealInfo.mealEndTime = mealTimeForId.mealEndTime;
        }
        matchMeal();
        return true;
    }

    /**
     * 重新匹配当前绑定餐品
     */
    private void matchMeal() {
        if (mCurrentBindingMealList.isEmpty() && BaseApplication.getInstance().isLocalMode()) {
            loadLocalMeal();
        }
        MealInfo startMeal = null;
        for (MealInfo info : mCurrentBindingMealList) {
            if (startMeal == null) {
                startMeal = info;
                continue;
            }
            MealInfo mealInfo1 = checkFoodTime(startMeal, info);
            if (mealInfo1 != null) {
                startMeal = mealInfo1;
                break;
            }
        }
        resetCurrentMealInfo(startMeal);
    }

    private void loadLocalMeal() {
        mCurrentBindingMealList.clear();
        List<MealInfo> currentMeals = WeightConfig.getCurrentMeals();
        if (currentMeals != null && !currentMeals.isEmpty()) {
            mCurrentBindingMealList.addAll(currentMeals);
        }
        mCurrentBindingMeals.clear();
        for (MealInfo mealInfo : mCurrentBindingMealList) {
            mCurrentBindingMeals.put(mealInfo.mealTimeId, mealInfo);
        }
    }

    private MealInfo checkFoodTime(MealInfo mealInfo, MealInfo mealInfo2) {
        boolean nowEffectiveDate = DateUtil.isNowEffectiveDate(mealInfo.mealStartTime, mealInfo.mealEndTime);
        if (nowEffectiveDate) {
            return mealInfo;
        }
        boolean nowEffectiveDate1 = DateUtil.isNowEffectiveDate(mealInfo.mealEndTime, mealInfo2.mealEndTime);
        if (nowEffectiveDate1) {
            return mealInfo2;
        }
        return null;
    }

    public void setFoodBound(String mealTimeId, MealInfo mListBean) {
        MealInfo mealInfo = mCurrentBindingMeals.get(mealTimeId);
        if (mealInfo == null) {
            mListBean.bound = false;
            return;
        }
        mListBean.bound = mealInfo.foodId.equals(mListBean.foodId);
    }

    public void bindFood(String mealTimeId, MealInfo mealInfo) {
        updateBindList(mealTimeId, mealInfo);
        getFoodInfo();
    }

    private static class ManagerHolder {
        private static final FoodManager instance = new FoodManager();
    }

    public interface FoodChangeCallBack {
        void onMealChange(MealInfo mealInfo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(BaseResponse event) {

    }
}
